﻿#if !SILVERLIGHT
using System;
using System.Threading;
using System.Windows.Threading;
#else
using System;
using System.Windows.Threading;
#endif

namespace Microsoft.Services.Clab.UI.Mvvmc
{
    public static class DispatcherProxy
    {
        public static Dispatcher Dispatcher { get; set; }

        public static void Invoke(Action action, DispatcherProxyPriority priority = DispatcherProxyPriority.Default)
        {
#if !SILVERLIGHT
            if (priority == DispatcherProxyPriority.Default && Thread.CurrentThread == Dispatcher.Thread)
            {
                action();
            }
            else
            {
                switch (priority)
                {
                    case DispatcherProxyPriority.Default:
                        Dispatcher.Invoke(action, DispatcherPriority.Normal);
                        break;
                    case DispatcherProxyPriority.BelowUIThreadPriority:
                        Dispatcher.Invoke(action, DispatcherPriority.Background);
                        break;
                    default:
                        break;
                }
            }
#else
            //priorities aren't supported on silverlight
            DispatcherOperation dispatcherOperation = Dispatcher.BeginInvoke(action);
#endif
        }

        public static void BeginInvoke(Action action, DispatcherProxyPriority priority = DispatcherProxyPriority.Default)
        {
#if !SILVERLIGHT
            switch (priority)
            {
                case DispatcherProxyPriority.Default:
                    Dispatcher.BeginInvoke(action);
                    break;
                case DispatcherProxyPriority.BelowUIThreadPriority:
                    Dispatcher.BeginInvoke(action, DispatcherPriority.Background);
                    break;
                default:
                    break;
            }
#else
            //priorities aren't supported on silverlight
            Dispatcher.BeginInvoke(action);
#endif
        }
    }

    public enum DispatcherProxyPriority
    {
        Default,
        BelowUIThreadPriority
    }
}
